// 修改后的 Security.jsx
import { useState } from 'react'
import { Form, Input, Button, message, Card, Row, Col } from 'antd'
import axios from 'axios'
import { getAuthToken } from '@/router/index.jsx' // 引入获取token的方法

export default function Security() {
  const [pwdForm] = Form.useForm()
  const [emailForm] = Form.useForm()
  const [pwdLoading, setPwdLoading] = useState(false)
  const [emailLoading, setEmailLoading] = useState(false)

  // 更新密码的API调用
  const updatePassword = async (values) => {
    try {
      const response = await axios.put(
          'http://localhost:8080/api/user/password',
          values,
          {
            headers: {
              Authorization: getAuthToken(),
              'Content-Type': 'application/json'
            }
          }
      )
      return response.data
    } catch (error) {
      throw new Error(error.response?.data?.message || '修改失败')
    }
  }

  // 绑定邮箱的API调用
  const updateEmail = async (email) => {
    try {
      const response = await axios.put(
          'http://localhost:8080/api/user/email',
          email, // 直接发送字符串
          {
            headers: {
              Authorization: getAuthToken(),
              'Content-Type': 'text/plain' // 注意这里使用 text/plain
            }
          }
      )
      return response.data
    } catch (error) {
      throw new Error(error.response?.data?.message || '绑定失败')
    }
  }

  const handlePassword = async (values) => {
    try {
      setPwdLoading(true)
      const response = await updatePassword({
        oldPassword: values.oldPassword,
        newPassword: values.newPassword
      })

      if (response.code === 200) {
        message.success('密码修改成功')
        pwdForm.resetFields()
      } else {
        message.error(response.msg || '密码修改失败')
      }
    } catch (error) {
      message.error(error.message)
    } finally {
      setPwdLoading(false)
    }
  }

  const handleEmail = async (values) => {
    try {
      setEmailLoading(true)
      const response = await updateEmail(values.email) // 直接发送邮箱字符串

      if (response.code === 200) {
        message.success('邮箱绑定成功')
      } else {
        message.error(response.msg || '邮箱绑定失败')
      }
    } catch (error) {
      message.error(error.message)
    } finally {
      setEmailLoading(false)
    }
  }

  return (
      <Row gutter={[24, 24]}>
        <Col xs={24} md={12}>
          <Card title="修改密码" bordered={false}>
            <Form form={pwdForm} onFinish={handlePassword}>
              <Form.Item
                  name="oldPassword"
                  label="原密码"
                  rules={[{ required: true, message: '请输入原密码' }]}
              >
                <Input.Password placeholder="当前密码" />
              </Form.Item>

              <Form.Item
                  name="newPassword"
                  label="新密码"
                  rules={[
                    { required: true, message: '请输入新密码' },
                    { min: 6, message: '密码至少6位' },
                    { max: 20, message: '密码最多20位' }
                  ]}
              >
                <Input.Password placeholder="6-20位字符" />
              </Form.Item>

              <Button
                  type="primary"
                  htmlType="submit"
                  loading={pwdLoading}
                  block
              >
                确认修改
              </Button>
            </Form>
          </Card>
        </Col>

        <Col xs={24} md={12}>
          <Card title="邮箱绑定" bordered={false}>
            <Form form={emailForm} onFinish={handleEmail}>
              <Form.Item
                  name="email"
                  rules={[
                    { required: true, message: '请输入邮箱地址' },
                    { type: 'email', message: '邮箱格式不正确' }
                  ]}
              >
                <Input placeholder="输入有效的邮箱地址" />
              </Form.Item>

              <Button
                  type="primary"
                  htmlType="submit"
                  loading={emailLoading}
                  block
              >
                绑定邮箱
              </Button>
            </Form>
          </Card>
        </Col>
      </Row>
  )
}